<?php


namespace App\Http\Controllers\Admin;


use App\Model\Goods;
use App\Model\GoodsMode;
use App\Model\GoodsSku;
use App\Model\GoodsSkuDetail;
use App\Tool\Json;
use App\Tool\Search;

class GoodsController extends AuthCheckController
{

    /**
     * 添加商品
     * Create by Peter
     * 2019/11/26 10:43:18
     * Email:904801074@qq.com
     * @return false|string
     */
    function goods_save()
    {


        try {

            \DB::beginTransaction();
            $post = request()->input();

            //存储商品数据
            $re = Goods::create($post);


            $goods_id = $re->id;

            //格式化模型
            $mode = json_encode(array_column($post['sku_name_list'], 'sku_name'));

            //存储商品模型
            GoodsMode::create(['goods_id' => $goods_id, 'mode' => $mode]);


            $sku_list = $post['sku_list'];

            foreach ($sku_list as $key => $value) {


                $goods_sku_re = GoodsSku::create([
                    'price' => $value['price'],
                    'num' => $value['num'],
                    'goods_id' => $goods_id,
                    'img' => $value['img']
                ]);


                $goods_sku_id = $goods_sku_re->id;

                foreach ($value['model'] as $k => $v) {

                    //必须在商品模型中（下同）
                    if(in_array($k,array_column($post['sku_name_list'], 'sku_name'))) {
                        GoodsSkuDetail::create([
                            'key' => $k,
                            'value' => $v,
                            'goods_sku_id' => $goods_sku_id
                        ]);
                    }

                }


            }

            \DB::commit();
            return Json::code(1, 'success');

        } catch (\Exception $exception) {

            \DB::rollBack();

            return Json::code(2, $exception->getMessage());

        }


    }


    /**
     * 更新商品
     * Create by Peter
     * 2019/11/26 10:43:32
     * Email:904801074@qq.com
     * @return false|string
     */
    function goods_update()
    {

        try {
            \DB::beginTransaction();

            $post = request()->input();

            $id = $post['id'] ?? 0;

            Goods::findOrFail($id)->fill($post)->save();

            //格式化模型
            $mode = json_encode(array_column($post['sku_name_list'], 'sku_name'));

            //一个商品只能有一个模型
            GoodsMode::where('goods_id', $id)->first()->fill(['mode' => $mode])->save();


            $sku_list = $post['sku_list'];

            foreach ($sku_list as $key => $value) {


                $goods_sku_re = GoodsSku::updateOrCreate(['id' => $value['id'] ?? 0],
                    [
                        'price' => $value['price'],
                        'num' => $value['num'],
                        'goods_id' => $id,
                        'img' => $value['img']
                    ]
                );


                $goods_sku_id = $goods_sku_re->id;

                GoodsSkuDetail::where('goods_sku_id', $goods_sku_id)->delete();

                foreach ($value['model'] as $k => $v) {

                    if(in_array($k,array_column($post['sku_name_list'], 'sku_name'))) {
                        GoodsSkuDetail::create([
                            'key' => $k,
                            'value' => $v,
                            'goods_sku_id' => $goods_sku_id
                        ]);
                    }

                }

            }


            \DB::commit();

            return Json::code(1, 'success');

        } catch (\Exception $exception) {


            \DB::rollBack();

            return Json::code(2, $exception->getMessage());

        }


    }

    /**
     * Create by Peter
     * 2019/11/27 09:22:47
     * Email:904801074@qq.com
     * @return Goods|array|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
     */
    function goods_list()
    {

        \DB::connection()->enableQueryLog();

        $list = Goods::with('category')->orderBy('id', 'desc');

        $custom=Search::searchList($list,request()->input('search','[]'));

        foreach ($custom as $key=>$value){


            if($value['dec']=='tip'){


                if($value['value']==2){

                    $list->where('recommend',1);
                }

            }


        }


        $new_goods = Goods::orderBy('id', 'desc')->limit(\Config::get('goods.new_goods_limit'))->get();

        $list = paginate($list, request()->input('p'));

        $new_id_array = array_column($new_goods->toArray(), 'id');

        foreach ($list['data'] as $key => $value) {

            $id = $value->id;

            if (in_array($id, $new_id_array)) {

                $list['data'][$key]['is_new'] = true;
            } else {
                $list['data'][$key]['is_new'] = false;
            }


        }

        $logs = \DB::getQueryLog();

        $list['sql']=$logs;

        $list['custom']=$custom;

        return $list;
    }

    /**
     * 商品上下架
     * Create by Peter
     * 2019/11/26 10:44:00
     * Email:904801074@qq.com
     * @return false|string
     */
    function goodsDownOrUp()
    {

        Goods::findOrFail(request()->input('id'))
            ->fill(['status' => request()->input('status')])
            ->save();

        return Json::code(1, 'success');


    }


    /**
     * 商品详情
     * Create by Peter
     * 2019/11/26 10:44:14
     * Email:904801074@qq.com
     * @return false|string
     */
    function getDetail()
    {

        $id = request()->input('id');


        $re = Goods::getDetail($id);


        return Json::code(1, 'success', $re);

    }


    /**
     * 商品删除
     * Create by Peter
     * 2019/11/26 10:44:21
     * Email:904801074@qq.com
     * @return false|string
     */
    function goods_delete()
    {

        $id = request()->input('id');

        Goods::destroy($id);

        return Json::code(1, 'success');


    }

    /**
     * 删除商品规格
     * Create by Peter
     * 2019/12/25 16:19:40
     * Email:904801074@qq.com
     */
    function delete_goods_sku(){


        $id=request()->input('id');



        $re=GoodsSku::destroy((int)$id);

        if(!$re) return Json::code(2,'删除失败！');

        return Json::code(1,'success');

    }

}
